<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="书名"
        style="width: 200px;"
        class="filter-item"
        clearable
      />
    
      <el-button type="primary" class="filter-item" @click="handleFilter">
        搜索
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading..."
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="80">
        <template #default="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>

      <el-table-column label="封面" width="100" align="center">
        <template #default="scope">
          <el-image 
            :src="scope.row.cover || defaultCover" 
            style="width: 80px; height: 100px"
            fit="cover"
            :preview-src-list="[scope.row.cover]">
            <template #error>
              <div class="image-placeholder">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>

      <el-table-column label="书名">
        <template #default="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>

      <el-table-column label="作者" width="120" align="center">
        <template #default="scope">
          {{ scope.row.author }}
        </template>
      </el-table-column>
 
      <el-table-column label="出版社" align="center">
        <template #default="scope">
          {{ scope.row.publish }}
        </template>
      </el-table-column>

      <el-table-column label="价格" width="110" align="center">
        <template #default="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>

      <el-table-column label="库存" width="80" align="center">
        <template #default="scope">
          {{ scope.row.stock }}
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 图书管理中的分页码 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="listQuery.page"
        v-model:page-size="listQuery.limit"
        :total="total"
        layout="total, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 图书表单对话框 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '添加图书' : '编辑图书'"
      v-model="dialogFormVisible"
    >
      <el-form
        ref="bookFormRef"
        :model="bookForm"
        :rules="bookRules"
        label-position="right"
        label-width="80px"
      >
        <el-form-item label="书名" prop="title">
          <el-input v-model="bookForm.title" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="bookForm.author" />
        </el-form-item>
        
        <el-form-item label="出版社" prop="publish">
          <el-input v-model="bookForm.publish" />
        </el-form-item>
   
        <el-form-item label="封面" prop="cover">
          <el-input v-model="bookForm.cover" placeholder="图片URL地址" />
          <el-upload
            class="upload-demo"
            action="/upload"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="handleAvatarSuccess"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
          <div class="cover-preview" v-if="bookForm.cover">
            <el-image 
              :src="bookForm.cover" 
              style="width: 80px; height: 100px"
              fit="cover">
            </el-image>
          </div>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="bookForm.price" :precision="2" :step="0.01" :min="0" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="bookForm.stock" :min="0" />
        </el-form-item>
       
        <el-form-item label="简介" prop="intro">
          <el-input v-model="bookForm.intro" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { bookAPI } from '../../utils/api'
import { Picture } from '@element-plus/icons-vue'

// 默认封面图片
const defaultCover = 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg'

// 图书数据列表
const list = ref([])
const total = ref(0)
const listLoading = ref(true)
const dialogFormVisible = ref(false)
const dialogStatus = ref('')
const bookFormRef = ref(null)

// 查询参数
const listQuery = reactive({
  page: 1,
  limit: 10,
  title: '',
  status: ''
})

// 表单数据
const bookForm = reactive({
  id: undefined,
  title: '',
  author: '',
  publish: '',
  cover: '',
  price: 0,
  stock: 0,
  status: 1,
  intro: ''
})

// 表单验证规则
const bookRules = {
  title: [{ required: true, message: '请输入书名', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }]
}

// 获取图书列表数据
const getList = async () => {
  listLoading.value = true
  
  try {
    const result = await bookAPI.getList(listQuery)
    
    if (result.code === 200) {
      list.value = result.data.list
      total.value = result.data.total
    }
  } catch (error) {
    console.error('获取图书列表失败:', error)
  } finally {
    listLoading.value = false
  }
}

// 处理搜索
const handleFilter = () => {
  listQuery.page = 1
  getList()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  listQuery.limit = val
  getList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  listQuery.page = val
  getList()
}


// 处理更新图书(编辑图书)
const handleUpdate = (row) => {
  resetForm()
  dialogStatus.value = 'update'
  
  console.log('原始行数据:', row)
  
  // 复制行数据到表单，并映射字段名称
  bookForm.id = row.id || row.b_id
  bookForm.title = row.title || row.bookname
  bookForm.author = row.author
  bookForm.publish = row.publish
  bookForm.cover = row.cover || row.img
  bookForm.price = row.price
  bookForm.stock = row.stock
  bookForm.status = row.status || 1
  bookForm.intro = row.intro
  
  console.log('映射后的表单数据:', bookForm)
  
  dialogFormVisible.value = true
}

// 处理状态变更
const handleStatusChange = async (row) => {
  try {
    await bookAPI.updateStatus({
      id: row.id,
      status: row.status
    })
    
    const statusText = row.status === 1 ? '上架' : '下架'
    ElMessage.success(`图书已${statusText}`)
  } catch (error) {
    // 如果发生错误，回滚状态
    row.status = row.status === 1 ? 0 : 1
    console.error('更新图书状态错误:', error)
  }
}

// 处理删除图书
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该图书吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await bookAPI.delete(row.id)
        ElMessage.success('删除成功')
        getList() // 重新获取列表
      } catch (error) {
        console.error('删除图书错误:', error)
      }
    })
    .catch(() => {
      // 取消删除
    })
}

// 上传图片前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 上传成功处理
const handleAvatarSuccess = (options) => {
  const formData = new FormData()
  formData.append('cover', options.file)
  
  // 调用实际的上传API
  fetch('http://localhost:3000/upload/bookcover', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${localStorage.getItem('token')}`
    },
    body: formData
  })
  .then(response => response.json())
  .then(result => {
    if (result.code === 200) {
      bookForm.cover = result.data.fullUrl
      ElMessage.success('封面上传成功')
    } else {
      ElMessage.error('封面上传失败: ' + result.message)
    }
  })
  .catch(error => {
    console.error('上传错误:', error)
    ElMessage.error('封面上传失败')
  })
}

// 提交表单
const submitForm = () => {
  bookFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 确保数值字段不为null
        bookForm.stock = bookForm.stock || 0
        bookForm.price = bookForm.price || 0
        
        console.log('提交的表单数据:', JSON.stringify(bookForm))
        
        if (dialogStatus.value === 'create') {
          await bookAPI.add(bookForm)
          ElMessage.success('添加成功')
        } else {
          await bookAPI.update(bookForm)
          ElMessage.success('更新成功')
        }
        
        dialogFormVisible.value = false
        getList() // 重新获取列表
      } catch (error) {
        console.error('提交表单错误:', error)
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (bookFormRef.value) {
    bookFormRef.value.resetFields()
  }
  
  bookForm.id = undefined
  bookForm.title = ''
  bookForm.author = ''
  bookForm.publish = ''
  bookForm.cover = ''
  bookForm.price = 0
  bookForm.stock = 0
  bookForm.status = 1
  bookForm.intro = ''
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.filter-container {
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  flex-shrink: 0;
}

.el-table {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  padding: 10px;
  text-align: right;
  background-color: #fff;
  flex-shrink: 0;
}

.image-placeholder {
  width: 80px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border: 1px dashed #d9d9d9;
  font-size: 24px;
  color: #909399;
}

.cover-preview {
  margin-top: 10px;
}
</style> 